package com.leyou.item.controller;

import com.leyou.common.pojo.PageResult;
import com.leyou.item.bo.SpuBo;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.Spu;
import com.leyou.item.pojo.SpuDetail;
import com.leyou.item.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class GoodsController {

    @Autowired
    GoodsService gs;

    @GetMapping("spu/page")
    public ResponseEntity<PageResult<SpuBo>> page(
            @RequestParam(value = "key",required = false) String key,
            @RequestParam(value = "saleable",required = false)Boolean saleable,
            @RequestParam(value = "page",defaultValue = "1")Integer page,
            @RequestParam(value = "rows",defaultValue = "5")Integer rows
    ){
        // 1.请求数据
        PageResult<SpuBo> list =  gs.querySpu(key,saleable,page,rows);

        // 2.判断集合中是否有值
        if(CollectionUtils.isEmpty(list.getItems())){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(list);

    }

    @PostMapping("goods")
    public ResponseEntity<Void> saveGoods(@RequestBody SpuBo spuBo){

        gs.saveGoods(spuBo);

        return ResponseEntity.ok().build();
    }
    @PutMapping("goods")
    public ResponseEntity<Void> editGoods(@RequestBody SpuBo spuBo){

        gs.editGoods(spuBo);

        return ResponseEntity.ok().build();
    }

    @GetMapping("spu/detail/{id}")
    public ResponseEntity<SpuDetail> getSpuDetail(@PathVariable("id") Long id){

        SpuDetail spuDetail = gs.getSpuDetailById(id);

        return ResponseEntity.ok(spuDetail);
    }

    // spu/detail/{id}   restful
    // list?id=xxx       普通的http的get请求
    @GetMapping("sku/list")
    public ResponseEntity<List<Sku>> getSkus(@RequestParam("id") Long id){
        List<Sku> skus = gs.getSkusById(id);
        // 库存在哪呢？ stock  去库存表中，根据sku的id进行库存的查询
        return ResponseEntity.ok(skus);
    }

    // 根据spuId，去查询spu对象
    @GetMapping("spu/{id}")
    public ResponseEntity<Spu> getSpus(@PathVariable("id")Long id){
        Spu spu = gs.getSpuById(id);

        return ResponseEntity.ok(spu);
    }

//    // 根据spu的id，brandid ， 查询brand对象
////    @GetMapping("bid/{id}")
////    public ResponseEntity<Brand> getBrand(@PathVariable("id")Long id){
////        Brand brand = gs.getBrand(id);
////
////        return ResponseEntity.ok(brand);
////    }

    @PostMapping("sku/{id}")
    public ResponseEntity<Sku> getSku(@PathVariable("id")Long id){
        Sku sku = gs.getSkuByid(id);

        return ResponseEntity.ok(sku);
    }

}
